/**
 * Copyright (C) 2009 alex <me@alex.0x08.org>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uber.netbsd.community.action;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.EmailTypeConverter;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import uber.netbsd.community.dao.Person;
import uber.netbsd.community.dao.PersonManager;
import uber.netbsd.community.dao.Role;

/**
 *
 * @author alex
 */
@UrlBinding("/action/Profile")
public class ProfileActionBean extends BaseActionBean {

    @ValidateNestedProperties({
        @Validate(field = "username", required = true, minlength = 3, maxlength = 15),
        @Validate(field = "password", minlength = 6, maxlength = 20),
        @Validate(field = "firstName", required = true, maxlength = 25),
        @Validate(field = "lastName", required = true, maxlength = 25),
        @Validate(field = "email", converter = EmailTypeConverter.class)
    })
    private Person user;

    /**
     * Validates that the two passwords entered match each other, and that the
     * username entered is not already taken in the system.
     */
    @ValidationMethod
    public void validate(ValidationErrors errors) {

        if ((!this.user.isNew() && PersonManager.getInstance().countExist(this.user.getUsername()) > 1)
                || (this.user.isNew() && PersonManager.getInstance().getPerson(this.user.getUsername()) != null)) {
            errors.add("user.username", new LocalizableError("usernameTaken"));
        }

    }

    /** Loads a bug on to the form ready for editing. */
    @DontValidate
    public Resolution preEdit() {

        if (user==null || user.getId()==null)
            user = new Person(); //create new stage
        else
            this.user = PersonManager.getInstance().getPerson(user.getId());

        return new ForwardResolution("/admin/profile.jsp");
    }

    
    public Person getUser() {
        return user;
    }

   

    public void setUser(Person u) {
        this.user = u;
    }

    @HandlesEvent("Back")
    @DontValidate
    public Resolution goBack() {


        return new RedirectResolution("/admin");
    }

    @HandlesEvent("Delete")
    @DontValidate
    public Resolution delete() {
        PersonManager.getInstance().deletePerson(user.getId());

        return new RedirectResolution("/admin/admin.jsp");
    }

    @HandlesEvent("Save")
    @DefaultHandler
    public Resolution saveChanges() {

        if (!user.isNew())
        {
            Person ruser = PersonManager.getInstance().getPerson(user.getId());
            ruser.fillFrom(user);
            user=ruser;
        }

        user.getRoles().clear();

        String key;
        for (Role r : Role.values()) {

            key = getContext().getRequest().getParameter(r.getName());
            if (key == null) {
                continue;
            }

            user.addRole(r);
        }

        PersonManager.getInstance().saveOrUpdate(user);

        getContext().getMessages().add(new SimpleMessage("Юзверь успешно сохранен. Такие дела."));

        return new RedirectResolution("/admin/admin.jsp");
    }
}
